package com.zhht.checkcop.log.convert;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.CallerData;
import ch.qos.logback.classic.spi.ILoggingEvent;

import com.alibaba.fastjson.JSON;
import com.zhbc.framework.utils.DateformatPattern;
import com.zhht.checkcop.log.LogMessageObject;

public class NativeLogerConverter extends ClassicConverter {

	 private DateFormat simpleFormat = new SimpleDateFormat(DateformatPattern.FMT_1.getPattern());
	 private static String hostName;
	 private static String localIp;
	 static {
		  InetAddress ia;
		try {
			ia = InetAddress.getLocalHost();
			hostName = ia.getHostName();
			localIp = ia.getHostAddress();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	 }
	 
	@Override
	public String convert(ILoggingEvent le) {
		  LogMessageObject log = new LogMessageObject();
		  log.setIp(localIp);
		  log.setHostName(hostName);
		  log.setTime(getTime(le));
		  log.setLevel(le.getLevel().toString());
		  log.setClassName(getFullyQualifiedName(le));
		  log.setMethodName(getMethodName(le));
		  log.setLine(getLineNumber(le));
		  log.setMessage(le.getFormattedMessage());
		  return JSON.toJSONString(log);
	}
	private String getTime(ILoggingEvent le) {
		  long timestamp = le.getTimeStamp();
		  return simpleFormat.format(new Date(timestamp));
	}

	private String getFullyQualifiedName(ILoggingEvent le) {
		StackTraceElement[] cda = le.getCallerData();
		if (cda != null && cda.length > 0) {
			return cda[0].getClassName();
		} else {
			return CallerData.NA;
		}
	}

	private String getLineNumber(ILoggingEvent le) {
		StackTraceElement[] cda = le.getCallerData();
		if (cda != null && cda.length > 0) {
			return Integer.toString(cda[0].getLineNumber());
		} else {
			return CallerData.NA;
		}
	}

	private String getMethodName(ILoggingEvent le) {
		StackTraceElement[] cda = le.getCallerData();
		if (cda != null && cda.length > 0) {
			return cda[0].getMethodName();
		} else {
			return CallerData.NA;
		}
	}
}
